import oss2
from django.conf import settings


class AliyunOss(object):

    def __init__(self):
        self.access_key_id = "LTAI5tEBX4FpJjzMwhuf1HXB"  # 从阿里云查询到的 AccessKey 的ID
        self.access_key_secret = "Dto69WDnZat8wyLElef5JwYSlrPT2x"  # 从阿里云查询到的 AccessKey 的Secret
        self.auth = oss2.Auth(self.access_key_id, self.access_key_secret)
        self.bucket_name = "luffycityzhang"  # 阿里云上创建好的Bucket的名称
        self.endpoint = "oss-cn-fuzhou.aliyuncs.com"  # 阿里云从Bucket中查询到的endpoint
        self.bucket = oss2.Bucket(self.auth, self.endpoint, self.bucket_name)
        # self.access_key_id = settings.OSS_ACCESS_KEY_ID
        # self.access_key_secret = settings.OSS_ACCESS_KEY_SECRET
        # self.auth = oss2.Auth(self.access_key_id, self.access_key_secret)
        # self.bucket_name = settings.OSS_BUCKET_NAME
        # self.endpoint = settings.OSS_ENDPOINT
        # self.bucket = oss2.Bucket(self.auth, self.endpoint, self.bucket_name)

    def put_object_from_file(self, name, file):
        """

        :param name: 在阿里云Bucket中要保存的文件名
        :param file: 本地图片的文件名
        :return:/Users/zhangdashuai/Pictures/OIP-C.jpeg
        """
        self.bucket.put_object_from_file(name, file)
        return "https://{}.{}/{}".format(self.bucket_name, self.endpoint, name)


if __name__ == '__main__':
    # 此处第一个参数 img[表情]tong1.png 中的img是阿里云的Bucket中事先创建好的test文件夹，第二个参数/images[表情]tong1.png是本地的图片katong1.png
    a = r"/Users/zhangdashuai/Pictures/OIP-C.jpeg"
    img_url = AliyunOss().put_object_from_file("uploads/avatar/2024/zhang.png", a)
    print(img_url)